<?php

namespace App\Admin\Actions\Batch;

use Dcat\Admin\Grid\BatchAction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\CabinetAlarm;

class CopyCabinetAlarm extends BatchAction
{
    // 确认弹窗信息
    public function confirm()
    {
        return '确定要复制已选中的报警设置吗？';
    }

    // 处理请求
    public function handle(Request $request)
    {
        // 获取选中的ID数组
        $keys = $this->getKey();
        $insertData = [];
        foreach ($keys as $alarmId) {
            $one = CabinetAlarm::find($alarmId);
            $oneData['project_id'] = $one['project_id'];
            $oneData['cabinet_pid'] = $one['cabinet_pid'];
            $oneData['name'] = $one['name'];
            $oneData['level'] = $one['level'];
            $oneData['condition'] = $one['condition'];
            $oneData['value'] = $one['value'];
            $oneData['active'] = $one['active'];
            $oneData['map_alarm'] = $one['map_alarm'];
            $oneData['created_at'] = date('Y-m-d H:i:s');
            $oneData['updated_at'] = date('Y-m-d H:i:s');
            array_push($insertData, $oneData);
        }
        $res = DB::table('xfy_cabinet_alarms')->insert($insertData);
        if ($res) {
            return $this->response()->success('复制成功')->refresh();
        } else {
            return $this->response()->error('复制失败')->refresh();
        }
    }

    public function actionScript(){
        $warning = __('No data selected!');

        return <<<JS
function (data, target, action) { 
    var key = {$this->getSelectedKeysScript()}

    if (key.length === 0) {
        Dcat.warning('{$warning}');
        return false;
    }

    // 设置主键为复选框选中的行ID数组
    action.options.key = key;
}
JS;
    }
}